package com.itclass.auth.util;


import com.itclass.auth.pojo.dto.UserDetailsDTO;
import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.JwtMap;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.Date;
import java.util.List;

public class JwtUtils {
    //盐值
    private static String signture="123456";

    // 默认1天
    public static final long time =  24 * 60;
    public static final long tokenTime = 60 * 1000 * time;


    //
    public static String getJwtToken(UserDetailsDTO userDetailsDTO, List<String> roles){
        JwtBuilder jwtBuilder = Jwts.builder();

        //第一部分：头部
        jwtBuilder.setHeaderParam("typ", "JWT");
        jwtBuilder.setHeaderParam("alg", "HS256");
        //第二部分：payload
        // 一些简单的数据放到 token 里面
        JwtMap jwtMap = new JwtMap();
        jwtMap.put("userName",userDetailsDTO.getUsername());

        jwtMap.put("roles",roles);
        jwtBuilder.setClaims(jwtMap);
        //获取当前系统的时间，加上时间
        long timeMillis = System.currentTimeMillis() + tokenTime;
        Date date = new Date(timeMillis);
        //设置这个令牌的过期时间
        jwtBuilder.setExpiration(date);
        //第三部分：Signature
        // SignatureAlgorithm.HS256：是你头部指定的加密算法，signture：是你要加密的盐值，最后生成Jwt
        String token = jwtBuilder.signWith(SignatureAlgorithm.HS256, signture).compact();

        return token;

    }

    /**
  * 获取令牌里面的信息userName
     *
     * @param token 令牌
     */
    public static String getUserName(String token) {
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey(signture).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        String userName = claims.get("userName", String.class);
        return userName;
    }


    /**
     *
     * @param token 令牌
     */
    public static Claims getClaims(String token) {
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey(signture).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();

        return claims;
    }
}
